#include "../server.hpp"
using std::cout;
using std::endl;

EventLoop loop;

uint64_t conn_id = 0;
std::unordered_map<uint64_t,PtrConnection> _conns;
void ConnectionDestroy(const PtrConnection& conn)
{
    _conns.erase(conn->Id());
}

void OnConnected(const PtrConnection& conn)
{
    logger->debug("NEW CONNECTION:%p",conn.get());
}

void OnMessage(const PtrConnection& conn, Buffer *buf)
{
    logger->debug("%s",buf->ReadPosition());
    buf->MoveReadOffset(buf->ReadAbleSize());
    std::string str = "Hello World";
    conn->Send(str.c_str(),str.size());
    conn->Shutdown();
}
void NewConnection(int fd)
{
    conn_id++;
    PtrConnection conn(new Connection(&loop,conn_id, fd));
    conn->SetMessageCallback (std::bind(OnMessage,std::placeholders::_1, std::placeholders::_2));
    conn->SetSrvClosedCallback(std::bind(ConnectionDestroy,std::placeholders::_1));
    conn->SetConnectedCallback(std::bind(OnConnected,std::placeholders::_1));
    conn->EnableInactiveRelease(10);//启动非活跃销毁功能
    conn->Established();
    _conns.insert(std::make_pair(conn_id, conn));
}
int main()
{
    srand(time(nullptr));
    Acceptor acceptor(&loop,8888);
    //为监听套接字，创建一个Channel进行事件的管理，以及事件的处理
    acceptor.SetAcceptCallback(std::bind(NewConnection,std::placeholders::_1));
    acceptor.Listen();
    while(1)
    {
        loop.Start();
    }
}
